package com.github.nuggets.service.impl;

import com.github.nuggets.entity.File;
import com.github.nuggets.model.exception.BizException;
import com.github.nuggets.repository.FileRepository;
import com.github.nuggets.service.FileService;
import com.github.nuggets.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.*;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Optional;

/**
 * @description:
 * @author: wangsj
 * @date: 2022/3/21 6:57 下午
 */
@Service
public class FileServiceImpl implements FileService {
    @Autowired
    public FileRepository fileRepository;
    @Value("${server.address}")
    private String serverAddress;
    @Value("${server.port}")
    private String serverPort;

    @Override
    public File saveFile(Long accountId, MultipartFile file) {

        try {
            File nuggetsFile = new File(file.getOriginalFilename(), file.getContentType(), file.getSize(), file.getBytes());
            nuggetsFile.setMd5(MD5Util.getMD5(file.getInputStream()));
            nuggetsFile.setAccountId(accountId);
            nuggetsFile.setPath(buildFileServicePath().toString());

            fileRepository.save(nuggetsFile);
            return nuggetsFile;

        } catch (IOException | NoSuchAlgorithmException ex) {
            throw new BizException("文件上传错误，" + ex.getMessage());
        }

    }

    @Override
    public void removeFile(String id) {
        fileRepository.deleteById(id);
    }

    @Override
    public Optional<File> getFileById(String id) {
        return fileRepository.findById(id);
    }

    @Override
    public List<File> listFilesByPage(Long accountId, int pageIndex, int pageSize) {


        File file = new File();
        file.setAccountId(accountId);

        //自定义条件查询
        //定义条件匹配器
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withIgnorePaths("_id")//忽略属性
                .withNullHandler(ExampleMatcher.NullHandler.IGNORE)
                .withIgnoreCase(true)//忽略大小写
                .withIgnorePaths("size")
                .withMatcher("accountId", ExampleMatcher.GenericPropertyMatchers.exact());


        Example<File> fileExample = Example.of(file,exampleMatcher);
        Sort sort = Sort.by(Direction.DESC, "uploadDate");
        Pageable pageable = PageRequest.of(pageIndex, pageSize, sort);

        Page<File> page = fileRepository.findAll(fileExample, pageable);

        return page.getContent();
    }


    private StringBuilder buildFileServicePath(){
        return new StringBuilder(serverAddress)
                .append(":")
                .append(serverPort)
                .append("/view/");
    }
}
